package weifei.wx.community.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weifei.web.Result;
import weifei.wx.community.entity.Avatar;
import weifei.wx.community.entity.User;
import weifei.wx.community.entity.WXSession;
import weifei.wx.community.mapper.AvatarMapper;
import weifei.wx.community.mapper.UserMapper;
import weifei.wx.community.service.UserService;
import weifei.wx.community.service.WXService;

import java.util.Date;
import java.util.HashMap;


@RestController
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private WXService wxService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AvatarMapper avatarMapper;



    @RequestMapping("/verifyAccessToken")
    public Result verifyAccessToken(@RequestParam("token") String accessToken)
    {
        if (WXService.verifyUserAccessToken(accessToken))
            return Result.success("success", true);
        return Result.success("success", false);
    }


    @RequestMapping("/login")
    public Result login(@Valid @NotNull String code)
    {
        String sessionText = this.wxService.get(
                "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&js_code=" +
                code +
                "&appid=" +
                WXService.APP_ID +
                "&secret=" +
                WXService.APP_SECRET
            );
        System.out.println(sessionText);

        ObjectMapper mapper = new ObjectMapper();
        WXSession wxSession;
        try {
            wxSession = mapper.readValue(sessionText, WXSession.class);
            System.out.println(wxSession.toString());
        } catch (JsonProcessingException e) {
            return Result.failed("内部错误");
        }

        if (wxSession.getOpenid() == null)
            return Result.failed();

        var userDTO = this.userService.getUserByWXOpenid(wxSession.getOpenid());
        if (userDTO == null)
        {
            var user = new User();
            user.setWxOpenid(wxSession.getOpenid());
            user.setNickname(user.getWxOpenid());
            if (this.userMapper.insert(user) == 0)
                return Result.failed();
            userDTO = this.userService.getUserByWXOpenid(wxSession.getOpenid());
        }

        String token = JWT.create()
            .withIssuedAt(new Date())
            .withExpiresAt(new Date(System.currentTimeMillis() + 86400000))   // 一天过期
            .withClaim("user_id", userDTO.getId())
            .withClaim("session_key", wxSession.getSessionKey())
            .sign(Algorithm.HMAC256(wxSession.getSessionKey() + WXService.TOKEN_PASSWORD_AFTER));     //使用HMAC算法

        // 保存 UserAccessToken
        WXService.saveUserAccessToken(userDTO.getId(), token);

        var map = new HashMap<String, Object>();
        map.put("accessToken", token);
        map.put("userDTO", userDTO);
        return Result.success("登录成功", map);
    }


    @RequestMapping("/uploadAvatar")
    public Result uploadAvatar(HttpServletRequest request, String content)
    {
        String token = request.getHeader("access_token");
        Long uid = JWT.decode(token).getClaim("user_id").asLong();

        Avatar avatar = this.userService.getAvatarByUserID(uid);
        if (avatar != null)
        {
            avatar.setContent(content);
            if (this.avatarMapper.update(avatar) == 0)
                return Result.failed();
            return Result.success("头像上传成功");
        }

        avatar = new Avatar();
        avatar.setId(uid);
        avatar.setUserId(uid);
        avatar.setContent(content);
        if (this.avatarMapper.insert(avatar) == 0)
            return Result.failed();
        return Result.success("头像上传成功");
    }



    @PostMapping("/updateUserInformation")
    public Result updateUserInformation(HttpServletRequest request, @RequestBody User user)
    {
        String token = request.getHeader("access_token");
        Long uid = JWT.decode(token).getClaim("user_id").asLong();
        String openid = JWT.decode(token).getClaim("wx_openid").asString();

        user.setId(uid);
        user.setWxOpenid(openid);
        System.out.println(user);

        if (this.userMapper.update(user) == 0)
            return Result.failed("错误");
        return Result.success();
    }


    @RequestMapping("/getNickname")
    public Result getNickname(@Valid @NotNull Long id)
    {
        var userDTO = this.userService.getUserByID(id);
        if (userDTO == null)
            return Result.failed();
        return Result.success("success", userDTO.getNickname());
    }


    @RequestMapping("/getUser")
    public Result getUser(@Valid @NotNull Long id)
    {
        if (id == null)
            return Result.failed("ID为空");

        var userDTO = this.userService.getUserByID(id);
        if (userDTO == null)
            return Result.failed();
        return Result.success("success", userDTO);
    }
}


